;(async function (){
    const express = require("express")
    const md5 = require("md5")
    const model = require("./db/model")
    const db = require("./db/db")
    const {resolve} = require("path")
    try{
        await db
        console.log("数据库连接成功")
        const app = express()
        app.use(express.static("./web"))
        app.use(express.urlencoded({extended: false}))
        app.set("view engine","ejs")
        app.set("views","../04-设置ejs/template")
        app.get("/registe",(req,res)=>{
            res.sendFile(resolve(__dirname,"web","view","registe.html"))
        })
        app.get("/login",(req,res)=>{
            res.sendFile(resolve(__dirname,"web","view","login.html"))
        })
        app.post("/registe",async (req,res)=>{
            const { username,password } = req.body
            try{
                await model.create({ username,password: md5(password) })
                res.redirect("http://localhost:5000/login")
            }catch(err){
                res.send("注册失败")
                console.log(err)
            }
        })
        app.post("/login",async function (req,res){
            const {username,password} = req.body
            try{
                const user = await model.findOne({username, password: md5(password)})
                if(user){
                    res.render("manager",user)
                }else{
                    res.send('登录失败了,请确认后重新登录')
                }
            }catch(err){
                res.send("登录失败，请稍后再试")
            }
        })
        app.listen(5000,(err)=>{
            if(err) console.log("服务器访问失败")
            else console.log("服务器访问成功")
        })
    }catch(err){
        console.log("数据库连接失败")
    }
})()